var $prev = null,
    leftBlocks = 16;

function init() {
    
    var fg = document.createDocumentFragment(),
        arr = [];
    
    for (var i = 1; i <= 8; i++) {
        arr.push(i);
        arr.push(i);
    }

    for (var i = 0; i < 16; i++) {
        var index = Math.floor(Math.random() * arr.length)
        $(fg).append('<div>' + arr[index] + '</div>');
        arr.splice(index, 1);
    }

    $('main').append(fg);
}

function attachEvent() {
    
    $('main').click(function (ev) {

        if (ev.target.nodeName === 'DIV') {
        
            var $el = $(ev.target);
        
            // make sure click the different blocks
            if (!$prev || $el.get(0) !== $prev.get(0)) {

                if ($prev && $el.text() === $prev.text()) {
                
                    $prev.removeClass('fliped').addClass('matched');
                    $el.addClass('matched');
                    $prev = null;
                   
                    leftBlocks -= 2;
                    if (leftBlocks === 0) {
                        setTimeout(function () {
                            swal("Good Job", "Well Done!", "success");
                        }, 200);
                    }

                } else {
                    
                    $('main div').removeClass('fliped');
                    $el.addClass('fliped');
                    $prev = $el;
                
                }
            }
        }
    });
}

$(window).ready(function () {

    // initial the blocks
    init();

    // add `click` event to main section
    attachEvent();

})
